package thread.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 原子读写一个引用对象
 *
 * @author liweimin
 * @date 2021/4/29 17:30
 * @since
 */
public class AtomicReferenceTest {
    static AtomicReference<String> atomicReference = new AtomicReference("123456");

    public static void main(String[] args) {
        //创建100个线程修改字符串 123456->654321
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                if (atomicReference.compareAndSet("123456", "654321")) {
                    System.out.println(Thread.currentThread().getName() + "===>字符串123456更改为654321");
                }
            }).start();
        }


        //创建100个线程修改字符串 654321->123456
        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                if (atomicReference.compareAndSet("654321", "123456")) {
                    System.out.println(Thread.currentThread().getName() + "===>字符串123456更改为654321");
                }
            }).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
